<?php
/**
 * 微信控制器
 * User: 54901
 * Date: 2018/12/2
 * Time: 15:56
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Env;
use think\Request;
use think\Session;
use think\Validate;
use EasyWeChat\Factory;
/**
 * 会员接口
 */
class WeChat extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';
    private $_WeChatConfig;
    private $_app;
    private $_model;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->_WeChatConfig = [
            'app_id'   => Env::get('wx_minipro.app_id', ''),
            'secret'   => Env::get('wx_minipro.secret', ''),
            'token'    => Env::get('wx_minipro.token', ''),
            'aes_key'  => Env::get('wx_minipro.aes_key', ''),
        ];
        $this->_app = Factory::miniProgram($this->_WeChatConfig);

        $this->_model = new \app\common\model\WeChat();
    }

    /**
     * 获取用户授权的微信信息
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function getOpenId(){
        $js_code = $this->request->request('js_code');
        $res = $this->_app->auth->session($js_code);
        if(!isset($res['errcode'])){
            //得到session_key  与 openid
            //进行用户数据储存
            Session::set('admin',$res);
            $this->success('请求成功',$res);
        }else{
            $this->error('请求失败');
        }
    }

    /**
     * 储存微信用户信息 或者获取用户信息
     */
    public function ToUserInfo(){
        $param = $this->request->request();
        $res = $this->_model->ToWxUser($param);
        if($res){
            $this->success(__('Sign up successful'),$res);
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }


}